import {AuthApi, type LoginRO, type TokenVO} from '@/api'
import axios from 'axios'

class AuthService {
    private axiosInstance = axios.create()
    private authApi = new AuthApi(undefined, import.meta.env.VITE_API_URL, this.axiosInstance);

    isLoggedIn: boolean = false;

    private saveToken(token: TokenVO){
        sessionStorage.setItem("access_token", token.access_token!)
        sessionStorage.setItem("refresh_token", token.refresh_token!)
    }

    private clearToken(){
        sessionStorage.removeItem("access_token")
        sessionStorage.removeItem("refresh_token")
    }

    login(loginRo: LoginRO){
        return this.authApi.login(loginRo).then((res)=>{
            this.isLoggedIn = true;
            this.saveToken(res.data)
            return res
        })
    }

    refreshToken(){
        let refreshToken = sessionStorage.getItem("refresh_token");
        return this.authApi.refresh(refreshToken!).then((res)=>{
            this.saveToken(res.data)
            return res
        })
    }

    logout(){
        this.clearToken()
        this.isLoggedIn = false;
    }
}

export const authService =  new AuthService()
